package cn.com.xuhx.testMapper;

import cn.com.xuhx.mapper.InsertMapper;
import cn.com.xuhx.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

/**
 * 插入SQL
 */
public class InsertTest {

    private SqlSession sqlSession = null;

    @Before
    public void getSQLSession() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
        //设置需要手动提交事务
        //sqlSession = build.openSession();
        //设置自动提交事务
        sqlSession = build.openSession(true);
    }

    @After
    public void closeSQLSession(){
        sqlSession.clearCache();
        sqlSession.close();
    }

    /**
     * 新增一个
     */
    @Test
    public void testAdd(){
        User user = new User("纪云禾", 22, "万花谷", "18115188111", "320672199110011084", new Date());
        InsertMapper mapper = sqlSession.getMapper(InsertMapper.class);
        mapper.addUser(user);
        //如果设置的是手动提交，则需要手动提交事务
        //sqlSession.commit();
    }

    /**
     * 新增一个
     */
    @Test
    public void testAdd2(){
        User user = new User("李四", 24, "上海市", "18115188223", "320672199110011087", new Date());
        InsertMapper mapper = sqlSession.getMapper(InsertMapper.class);
        mapper.addUser2(user);
        System.out.println(user.getId());
    }
}
